import { Component } from '@angular/core';
import { NavController, NavParams,LoadingController } from 'ionic-angular';
import { AlertController } from 'ionic-angular';
import { DeviceProvider } from '../../../providers/service/device'
import { FileTransfer, FileUploadOptions, FileTransferObject } from '@ionic-native/file-transfer';
import { File } from '@ionic-native/file';
import { Camera, CameraOptions } from '@ionic-native/camera';
import {ActionSheetController} from "ionic-angular/index";
import { AppGlobal } from '../../../providers/appGlobal'

/**
 * Generated class for the DeviceWhPage page.
 *
 * See https://ionicframework.com/docs/components/#navigation for more info on
 * Ionic pages and navigation.
 */

@Component({
  selector: 'page-device-wh',
  templateUrl: 'device-wh.html',
})
export class DeviceWhPage {

  constructor(public navCtrl: NavController,
              public navParams: NavParams,
              public deviceProvider: DeviceProvider,
              public loadingCtrl: LoadingController,
              public transfer: FileTransfer,
              public file: File,
              public actionSheetCtrl: ActionSheetController,
              public camera: Camera,
              public alertCtrl: AlertController) {
  }

  //设备数据
    actionParam = {
            id:0,
            physicalCode: '',
            deviceCategoryId: '1',
            name: '',
            farmId: '',
            status: '0',
            logicalCode: '',
            provinceCode: '',
            cityCode: '',
            districtCode: '',
            expireTime: '',
            planFlow: '',
            longitude: '',
            latitude: '',
            address: '',
            salesMan: '',
            salesPhone: '',
            maintenanceMan: '',
            maintenancePhone: '',
            buildMan: '',
            buildPhone: '',
            buildTime: '',
            description: '',
            imageUrl: ''
        }
  //设备编号
    id: any;
  type = null;
  provinceArr = [
    {
      "provinceCode": "110000",
      "name": "北京市",
      "id": 1
    },
    {
      "provinceCode": "120000",
      "name": "天津市",
      "id": 2
    },
    {
      "provinceCode": "130000",
      "name": "河北省",
      "id": 3
    },
    {
      "provinceCode": "140000",
      "name": "山西省",
      "id": 4
    },
    {
      "provinceCode": "150000",
      "name": "内蒙古自治区",
      "id": 5
    },
    {
      "provinceCode": "210000",
      "name": "辽宁省",
      "id": 6
    },
    {
      "provinceCode": "220000",
      "name": "吉林省",
      "id": 7
    },
    {
      "provinceCode": "230000",
      "name": "黑龙江省",
      "id": 8
    },
    {
      "provinceCode": "310000",
      "name": "上海市",
      "id": 9
    },
    {
      "provinceCode": "320000",
      "name": "江苏省",
      "id": 10
    },
    {
      "provinceCode": "330000",
      "name": "浙江省",
      "id": 11
    },
    {
      "provinceCode": "340000",
      "name": "安徽省",
      "id": 12
    },
    {
      "provinceCode": "350000",
      "name": "福建省",
      "id": 13
    },
    {
      "provinceCode": "360000",
      "name": "江西省",
      "id": 14
    },
    {
      "provinceCode": "370000",
      "name": "山东省",
      "id": 15
    },
    {
      "provinceCode": "410000",
      "name": "河南省",
      "id": 16
    },
    {
      "provinceCode": "420000",
      "name": "湖北省",
      "id": 17
    },
    {
      "provinceCode": "430000",
      "name": "湖南省",
      "id": 18
    },
    {
      "provinceCode": "440000",
      "name": "广东省",
      "id": 19
    },
    {
      "provinceCode": "450000",
      "name": "广西壮族自治区",
      "id": 20
    },
    {
      "provinceCode": "460000",
      "name": "海南省",
      "id": 21
    },
    {
      "provinceCode": "500000",
      "name": "重庆市",
      "id": 22
    },
    {
      "provinceCode": "510000",
      "name": "四川省",
      "id": 23
    },
    {
      "provinceCode": "520000",
      "name": "贵州省",
      "id": 24
    },
    {
      "provinceCode": "530000",
      "name": "云南省",
      "id": 25
    },
    {
      "provinceCode": "540000",
      "name": "西藏自治区",
      "id": 26
    },
    {
      "provinceCode": "610000",
      "name": "陕西省",
      "id": 27
    },
    {
      "provinceCode": "620000",
      "name": "甘肃省",
      "id": 28
    },
    {
      "provinceCode": "630000",
      "name": "青海省",
      "id": 29
    },
    {
      "provinceCode": "640000",
      "name": "宁夏回族自治区",
      "id": 30
    },
    {
      "provinceCode": "650000",
      "name": "新疆维吾尔自治区",
      "id": 31
    },
    {
      "provinceCode": "710000",
      "name": "台湾省",
      "id": 32
    },
    {
      "provinceCode": "810000",
      "name": "香港特别行政区",
      "id": 33
    },
    {
      "provinceCode": "820000",
      "name": "澳门特别行政区",
      "id": 34
    }
  ];
  cityArr = [];
  districtArr = [];
  farmArr = [];
  ionViewDidLoad() {
    console.log('ionViewDidLoad DeviceWhPage');
    this.type = this.navParams.data.type;       //类型  1 添加  2维护
    if(this.type == 2){
         this.id = this.navParams.data.id;
         this.loadDeviceDetail(this.id);
      }
    this.getFarmList();
  }

  //文件选择
  chooseFile(){

      var _this = this;

      let actionSheet = this.actionSheetCtrl.create({
          title: '选择',
          buttons: [
              {
                  text: "选择照片",
                  handler: () => {
                      chooseType(0);
                  }
              },
              {
                  text: "拍照",
                  handler: () => {
                      chooseType(1);
                  }
              }
          ]

      });
      actionSheet.present();


      function chooseType(type){

          var sourceType = _this.camera.MediaType.PICTURE;
          if (type == 1) {
              sourceType = _this.camera.PictureSourceType.CAMERA;
          }
          var options = {
              quality: 50,
              destinationType: _this.camera.DestinationType.FILE_URI,
              encodingType: _this.camera.EncodingType.JPEG,
              mediaType: _this.camera.MediaType.PICTURE,
              // popoverOptions: CameraPopoverOptions,
              saveToPhotoAlbum: false,
              allowEdit: false,
              correctOrientation: true,
              sourceType: sourceType,//拍照时，此参数必须有，否则拍照之后报错，照片不能保存
          };
          _this.camera.getPicture(options).then((imgPath) => {
              alert(imgPath);
              //let base64Image = 'data:image/jpeg;base64,' + imgPath;
              _this.actionParam.imageUrl = imgPath;
          }, (err) => {
              alert("选择失败")
          });
      }


  }

    saveFile(){
        const fileTransfer: FileTransferObject = this.transfer.create();
        let options: FileUploadOptions = {
            fileKey: 'file',
            //fileName: 'name.jpg',
            headers: {
                'Authorization':  AppGlobal.getInstance().getToken()
            }
        }

        fileTransfer.upload(this.actionParam.imageUrl , 'http://www.baidu.com', options)
            .then((data) => {
                // success
                alert(data);
            }, (err) => {
                // error
                alert(err);
            })
    }

    loadDeviceDetail(id){
        this.deviceProvider.getDetail(this.id).then((res: any) => {
            console.log(res);
            this.actionParam.provinceCode = res.provinceCode;
            this.changeProvince();
            this.actionParam.cityCode = res.cityCode;
            this.changeCity();
            this.actionParam.districtCode = res.districtCode;
            this.actionParam = res;
            if(res.expireTime != null)
                this.actionParam.expireTime = this.dateFormat(res.expireTime.toString(),"yyyy-MM-dd");
            if(res.buildTime)
                this.actionParam.buildTime = this.dateFormat(res.buildTime.toString(),"yyyy-MM-dd");
        }, err => {
        })
    }


  /**
   * 改变省份方法
   */
  changeProvince(){
    var proCode = this.actionParam.provinceCode;
    var thisObj = this;

    this.deviceProvider.getCityList(proCode).then((res: any) => {
      this.cityArr = res;
        //thisObj.actionParam.cityCode = this.cityArr[0].cityCode || '';
        //thisObj.actionParam.districtCode = '';
        //thisObj.changeCity()
    }, err => {
      console.log(err);
    });
  }

  /**
   * 改变地市方法
   */
  changeCity(){
    var cityCode = this.actionParam.cityCode;
      var thisObj = this;
    this.deviceProvider.getDistrictList(cityCode).then((res: any) => {
      this.districtArr = res;
        //thisObj.actionParam.districtCode = this.districtArr[0].districtCode || '';
    }, err => {
      console.log(err);
    });
  }

  //获取农场
    getFarmList(){
        this.deviceProvider.getFarmList().then((res: any) => {
            this.farmArr = res;
        }, err => {
            console.log(err);
        });
    }

    //提交数据
    submitData(){
        if(this.actionParam.buildTime.indexOf("a") != -1)
            this.actionParam.buildTime = '';

        if(this.VerificationForm()){
            let loading = this.loadingCtrl.create({
                content: '正在保存，请稍等...'
            });
            loading.present();

            if(this.actionParam.buildTime != '')
                this.actionParam.buildTime += " 00:00:00"

            if(this.type == 1){
                this.deviceProvider.addDevice(this.actionParam).then(res => {
                    loading.setContent("保存成功！");
                    this.type = 2;
                    setTimeout(() => {
                        loading.dismiss();
                    }, 100);
                }, err => {
                    loading.setContent("保存失败！");
                    setTimeout(() => {
                        loading.dismiss();
                    }, 100);
                })
            }
            else{
                this.deviceProvider.updateDevice(this.actionParam).then(res => {
                    loading.setContent("保存成功！");
                    setTimeout(() => {
                        loading.dismiss();
                    }, 100);
                }, err => {
                    loading.setContent("保存失败！");
                    setTimeout(() => {
                        loading.dismiss();
                    }, 100);
                })
            }
        }
    }

    showAlert(str) {
        let alert = this.alertCtrl.create({
            title: '提示',
            subTitle: str,
            buttons: ['OK']
        });
        alert.present();
    }

     // 对Date的扩展，将 Date 转化为指定格式的String
     // 月(M)、日(d)、小时(h)、分(m)、秒(s)、季度(q) 可以用 1-2 个占位符，
     // 年(y)可以用 1-4 个占位符，毫秒(S)只能用 1 个占位符(是 1-3 位的数字)
     // 例子：
     // (new Date()).Format("yyyy-MM-dd hh:mm:ss.S") ==> 2006-07-02 08:09:04.423
     // (new Date()).Format("yyyy-M-d h:m:s.S")      ==> 2006-7-2 8:9:4.18
     dateFormat (dateStr,fmt) {
        var date = new Date(dateStr);
        var o = {
            "M+": date.getMonth() + 1, //月份
            "d+": date.getDate(), //日
            "h+": date.getHours(), //小时
            "m+": date.getMinutes(), //分
            "s+": date.getSeconds(), //秒
            "q+": Math.floor((date.getMonth() + 3) / 3), //季度
        };
        if (/(y+)/.test(fmt)) fmt = fmt.replace(RegExp.$1, (date.getFullYear() + "").substr(4 - RegExp.$1.length));
        for (var k in o)
            if (new RegExp("(" + k + ")").test(fmt)) fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
        return fmt;
    }

    VerificationForm(){
        if(this.actionParam.physicalCode == ""){
            this.showAlert("编号不能为空！");
            return false;
        }else if(this.actionParam.name == ""){
            this.showAlert("名称不能为空！");
            return false;
        }else if(this.actionParam.provinceCode == ""){
            this.showAlert("省份不能为空！");
            return false;
        }else if(this.actionParam.cityCode == ""){
            this.showAlert("地市不能为空！");
            return false;
        }else if(this.actionParam.districtCode == ""){
            this.showAlert("区县不能为空！");
            return false;
        }else if(this.actionParam.farmId == ""){
            this.showAlert("农场不能为空！");
            return false;
        }else if(this.actionParam.logicalCode == ""){
            this.showAlert("SIM卡号不能为空！");
            return false;
        }else if(this.actionParam.expireTime == ""){
            this.showAlert("SIM有效期不能为空！");
            return false;
        }
        return true;
    }

}
